<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
    width="30%"
    align-center
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="用户ID">
        <ElInput v-model="formData.userId" disabled />
      </ElFormItem>
      <ElFormItem label="用户名">
        <ElInput v-model="formData.nickname" disabled />
      </ElFormItem>
      <ElFormItem label="邮箱">
        <ElInput v-model="formData.email" disabled />
      </ElFormItem>
      <ElFormItem label="用户角色" prop="role">
        <ElSelect v-model="formData.role" placeholder="请选择用户角色">
          <ElOption
            v-for="option in roleOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { fetchUpdateUserRole } from '@/api/system-manage'
  import type { FormInstance, FormRules } from 'element-plus'

  interface Props {
    visible: boolean
    type: string
    userData?: Partial<Api.SystemManage.UserListItem>
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 角色选项列表
  const roleOptions = [
    { label: '普通用户', value: 'user' },
    { label: '管理员', value: 'admin' }
  ]

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  // 表单实例
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive({
    userId: '',
    nickname: '',
    email: '',
    role: '' as 'user' | 'admin' | ''
  })

  // 表单验证规则
  const rules: FormRules = {
    role: [{ required: true, message: '请选择用户角色', trigger: 'change' }]
  }

  /**
   * 初始化表单数据
   * 根据对话框类型（新增/编辑）填充表单
   */
  const initFormData = () => {
    const row = props.userData

    Object.assign(formData, {
      userId: row?.id || '',
      nickname: row?.nickname || '',
      email: row?.email || '',
      role: row?.role || ''
    })
  }

  /**
   * 监听对话框状态变化
   * 当对话框打开时初始化表单数据并清除验证状态
   */
  watch(
    () => [props.visible, props.type, props.userData],
    ([visible]) => {
      if (visible) {
        initFormData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  /**
   * 提交表单
   * 验证通过后调用 API 更新用户角色
   */
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()

      // 调用更新角色接口
      if (formData.userId && formData.role) {
        await fetchUpdateUserRole(formData.userId, formData.role as 'user' | 'admin')
        ElMessage.success('用户角色更新成功')
        dialogVisible.value = false
        emit('submit')
      }
    } catch (error: any) {
      console.error('更新用户角色失败:', error)
      if (error !== false) {
        // 非表单验证失败
        ElMessage.error(error?.message || '更新失败，请稍后重试')
      }
    }
  }
</script>
